package web.controller.common;

import common.consts.ContentType;
import common.validation.ValidationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.AccountService;
import service.ServiceResponse;
import web.Routes;
import web.controller.Base;
import web.req.LoginRequest;
import web.security.JWT;


/**
 * Created by Ace Yin on 2015/5/29 0029.
 */
@RestController
@RequestMapping(Routes.Common.LOGIN)
public class Login extends Base {

    @Autowired
    private AccountService accountService;

    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse login(@RequestBody LoginRequest request) {
        ValidationResult result = request.validate();
        if (!result.isSuccess()) {
            return fail(result.getMessage());
        }

        ServiceResponse response = accountService.login(request.getUsername(), request.getPassword(), request.ip());

        if (response.isFailed()) {
            return response;
        }

        Long id = response.get("id", Long.class);
        String password = response.getTemp("password", String.class);

        String auth = JWT.create(id, password);
        response.with("accessToken", auth);

        return response;
    }
}
